package com.quark.common.security.code;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.quark.result.RequestResult;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张高昌
 * @date 2022/02/12 22:18
 * @description 对登录请求拦截验证码是否正确
 * 继承spring中的OncePerRequestFilter，确保每次请求调用一次过滤器
 * InitializingBean 实现此接口中的 afterPropertiesSet 初始化方法在其中初始化图片验证码拦截路径
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter implements InitializingBean {

    private final static String login_url = "/api/login";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        if (login_url.equals(request.getRequestURI()) && "POST".equalsIgnoreCase(request.getMethod())) {
            // 验证码验证
            String imageCode = request.getParameter("code");
            String genCaptcha = (String) request.getSession().getAttribute("code");
            //filter如果抛出异常 全局异常无法捕获到，所以采用了这个方法
            if (StrUtil.isEmpty(imageCode)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json");
                response.getWriter().print(JSONUtil.parse(RequestResult.validateFailed("验证码不能为空")));
                response.getWriter().flush();
                return;
            }
            if (genCaptcha == null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json");
                response.getWriter().print(JSONUtil.parse(RequestResult.validateFailed("请重新刷新验证码")));
                response.getWriter().flush();
                return;
            }
            if (!genCaptcha.equals(imageCode.toLowerCase())) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json");
                response.getWriter().print(JSONUtil.parse(RequestResult.validateFailed("验证码错误")));
                response.getWriter().flush();
                return;
            }

        }
        filterChain.doFilter(request, response);
    }


}
